from fastapi import APIRouter, HTTPException
from typing import List

# 绝对导入
from app.models.schemas import ChatRequest, ChatResponse, ModelInfo
from app.services.ai_service import AIService
from app.services.model_manager import ModelManager

router = APIRouter()
ai_service = AIService()
model_manager = ModelManager()


@router.post("/chat", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest):
    """
    Send a chat message and get AI response
    """
    try:
        # Validate model
        if not model_manager.is_model_available(request.model):
            raise HTTPException(
                status_code=400,
                detail=f"Model {request.model} is not available"
            )

        # Process chat request
        response = await ai_service.process_chat(
            messages=request.messages,
            model=request.model,
            temperature=request.temperature,
            max_tokens=request.max_tokens
        )

        return response

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/models", response_model=List[ModelInfo])
async def get_available_models():
    """
    Get list of available AI models
    """
    return model_manager.get_available_models()


@router.get("/models/{model_name}", response_model=ModelInfo)
async def get_model_info(model_name: str):
    """
    Get information about a specific model
    """
    model_info = model_manager.get_model_info(model_name)
    if not model_info:
        raise HTTPException(status_code=404, detail="Model not found")
    return model_info